<template>
    <div
        v-show="!boxShow"
        class="common-show-box"
        style="position: absolute; top: var(--system-map-item-padding); right: 0"
    >
        <img class="common-show-icon" src="@/assets/images/common/shrink.png" @click="boxShow = true" />
    </div>
    <transition name="slide">
        <div v-show="boxShow" class="common-box">
            <div class="common-box-title">
                <div class="common-box-text">工程查询/编辑</div>
                <img class="common-box-title-icon" src="@/assets/images/common/shrink.png" @click="boxShow = false" />
            </div>
            <div class="common-box-title2">
                <img class="title2-icon" src="@/assets/images/common/title-icon.png" alt="" />
                <div class="common-box-text2">条件选择</div>
            </div>
            <div class="common-box-item" style="width: 100%; min-width: 20vw; align-items: revert">
                <el-form
                    ref="formRef"
                    :model="form"
                    :rules="rules"
                    label-width="8rem"
                    size="default"
                    class="demo-ruleForm"
                >
                    <el-form-item label="图层选择" required>
                        <el-col :span="16">
                            <el-form-item prop="layer">
                                <el-select v-model="form.layer">
                                    <el-option
                                        v-for="item in layerList"
                                        :key="item.name"
                                        :label="item.name"
                                        :value="item.name"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-form-item>

                    <el-form-item size="default">
                        <el-checkbox-group v-model="queryType" @change="queryTypeChange">
                            <el-checkbox v-if="spatialQueryModel" value="空间查询">空间查询</el-checkbox>
                            <el-checkbox v-if="conditionalQueryModel" value="条件查询">条件查询</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                    <!------------------------------------------------------- 空间查询 ------------------------------------------------------>
                    <div v-if="spatialQuery" class="common-box-item" style="width: 100%">
                        <div>
                            <el-button @click="queryDraw('Point')">点缓冲区</el-button>
                            <el-button @click="queryDraw('LineString')">线缓冲区</el-button>
                            <el-button @click="queryDraw('Circle')">圆形</el-button>
                            <el-button @click="queryDraw('Rectangle')">矩形</el-button>
                            <el-button @click="queryDraw('Polygon')">多边形</el-button>
                        </div>
                    </div>
                    <!------------------------------------------------------- 空间查询 ------------------------------------------------------>

                    <!------------------------------------------------------- 条件查询 ------------------------------------------------------>
                    <div v-if="conditionalQuery" class="query-builder">
                        <!-- SQL 查询输入框 -->
                        <div class="input-box">
                            <input v-model="queryText" placeholder="拼接 SQL 查询语句" />
                        </div>

                        <div class="select-body">
                            <!-- 字段列表 -->
                            <div class="field-values">
                                <div class="field-label">字段值：</div>
                                <div
                                    v-for="(field, index) in fieldsKeys"
                                    :key="index"
                                    class="field-value"
                                    @dblclick="addFieldToQuery(field)"
                                >
                                    {{ field }}
                                </div>
                            </div>

                            <!-- 条件符号选择框 -->
                            <div class="conditions">
                                <div class="condition-label">条件符号：</div>
                                <div
                                    v-for="(condition, index) in conditions"
                                    :key="index"
                                    class="condition"
                                    @dblclick="addConditionToQuery(condition)"
                                >
                                    {{ condition }}
                                </div>
                            </div>

                            <!-- 字段内容选择框 -->
                            <div class="field-values">
                                <div class="field-label">字段内容：</div>
                                <div
                                    v-for="(value, index) in fieldValues"
                                    :key="index"
                                    class="field-value"
                                    @dblclick="addValueToQuery(value)"
                                >
                                    {{ value }}
                                </div>
                            </div>
                        </div>
                    </div>

                    <el-form-item v-show="conditionalQuery" size="default">
                        <el-button type="primary" @click="submitForm(formRef, queryText)">确定</el-button>
                        <el-button @click="queryText = ''">重置</el-button>
                    </el-form-item>
                    <!------------------------------------------------------- 条件查询 ------------------------------------------------------>

                    <el-form-item v-show="!spatialQuery && !conditionalQuery" size="default">
                        <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
                        <el-button @click="resetForm(formRef)">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- <div class="common-box-item" style="width: 100%">
                <div>
                    <el-button @click="addDmProject()">DM工程</el-button>
                    <el-button @click="removeDmProject()">移除工程</el-button>
                    <el-button @click="draw('Point')">加点</el-button>
                    <el-button @click="draw('LineString')">加线</el-button>
                    <el-button @click="draw('Polygon')">加面</el-button>
                </div>
            </div> -->

            <!---------------------------------------------- 属性编辑查看表格 --------------------------------------------->
            <div v-show="tableShow" class="common-box-title2">
                <img class="title2-icon" src="@/assets/images/common/title-icon.png" alt="" />
                <div class="common-box-text2">属性表</div>
            </div>
            <Transition name="fade">
                <div v-show="tableShow" class="common-box-item">
                    <div class="data-table" style="min-width: 20vw">
                        <div style="max-height: 29vh; overflow: auto">
                            <table border="1">
                                <thead>
                                    <tr>
                                        <th v-for="(key, index) in fieldsKeys" :key="index">{{ key }}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(item, rowIndex) in pagedTableData" :key="rowIndex">
                                        <td
                                            v-for="(value, cellIndex) in fieldsKeys"
                                            :key="cellIndex"
                                            @dblclick="
                                                editCell(rowIndex, cellIndex, item.FIELDS[value], item, {
                                                    fldname: value,
                                                    fldval: item.FIELDS[value]
                                                })
                                            "
                                        >
                                            <!-- editCell函数中参数分别为行索引，列索引，单元格值，行数据，用于服务端修改数据的相应格式参数 -->
                                            <div
                                                v-if="
                                                    !isEditing ||
                                                    editingCell !== `${rowIndex}-${cellIndex}` ||
                                                    fieldsKeys[cellIndex] === 'dmgis_id'
                                                "
                                                :id="'edit-target' + rowIndex + '-' + cellIndex"
                                                :title="fieldsKeys[cellIndex] + ':' + item.FIELDS[value]"
                                                style="width: 100%; font-size: 0.75vw; color: var(--theme-text1)"
                                            >
                                                {{ item.FIELDS[value] }}
                                            </div>
                                            <input
                                                v-else
                                                id="edit-input"
                                                v-model="editData"
                                                type="text"
                                                style="width: auto; font-size: 0.75vw; color: var(--theme-text1)"
                                                autocomplete="off"
                                                @blur="
                                                    saveEdit(
                                                        item,
                                                        {
                                                            fldname: value,
                                                            fldval: editData
                                                        },
                                                        rowIndex,
                                                        cellIndex
                                                    )
                                                "
                                            />
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div
                        v-show="!tableData.length"
                        class="data-table"
                        style="min-width: 20vw; color: var(--theme-text1)"
                    >
                        暂无数据
                    </div>
                    <div class="data-table" style="min-width: 20vw">
                        <el-config-provider :locale="zhCn">
                            <el-pagination
                                size="default"
                                :page-sizes="[10, 20, 30, 40]"
                                :page-size="pageSize"
                                :current-page="currentPage"
                                :total="totalItems"
                                layout="total, sizes, prev, pager, next, jumper"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                            >
                            </el-pagination>
                        </el-config-provider>
                    </div>
                </div>
            </Transition>
            <!---------------------------------------------- 属性编辑查看表格 --------------------------------------------->
        </div>
    </transition>

    <!---------------------------------------------- 矢量属性添加弹窗 --------------------------------------------->
    <el-dialog v-model="dialogFormVisible" title="属性表" width="500">
        <el-form :model="formData">
            <el-form-item v-for="item in fieldsKeys" v-show="item != 'dmgis_id'" :key="item" :label="item + ':'">
                <el-input v-model="formData[item]" placeholder="请输入内容"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addVector"> 确定 </el-button>
            </div>
        </template>
    </el-dialog>
    <!---------------------------------------------- 矢量属性添加弹窗 --------------------------------------------->

    <!---------------------------------------------- 缓冲区半径弹窗 --------------------------------------------->
    <el-dialog v-model="dialogFormVisible1" title="缓冲区半径" width="500">
        <el-form ref="bufferFormRef" :model="formData1" :rules="rules1">
            <el-form-item label="缓冲区半径(km):" prop="radius">
                <el-input v-model="formData1.radius" placeholder="请输入缓冲区半径(km)"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible1 = false">取消</el-button>
                <el-button type="primary" @click="createBuffer(bufferFormRef)"> 确定 </el-button>
            </div>
        </template>
    </el-dialog>
    <!---------------------------------------------- 缓冲区半径弹窗 --------------------------------------------->
</template>
<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn';
let { prjName, spatialQueryModel, conditionalQueryModel, editModel } = defineProps({
    prjName: {
        type: String,
        default: ''
    },
    spatialQueryModel: {
        type: Boolean,
        default: false // 设置默认值为 false
    },
    conditionalQueryModel: {
        type: Boolean,
        default: false
    },
    editModel: {
        type: Boolean,
        default: false
    }
});

import { computed } from 'vue';

// 初始化map
import { useMapStoreHook } from '@/store/map';
const mapStore = useMapStoreHook();
const { olMap, extent } = storeToRefs(mapStore);

import ImageLayer from 'ol/layer/Image';
//引入dm脚本
import dmgis from '@/map/dmgis.js';

/*------------------------------------------------------条件查询--------------------------------------------------------- */
let boxShow = ref(true);
/*------------------------工程初始化----------------------------*/
let layerList = ref([]);
//dimgis工程地图chinaProject,/dmgis用来配置代理
let dmProjectLayer = new dmgis.olmap.ServiceLayer(prjName, '/dmgis', {
    minZoom: 1,
    tileSize: [256, 256]
});
//获取工程的所有图层
dmProjectLayer.InitService().then((res) => {
    layerList.value = res.RESPONSE.SERVER.LAYER;
});
let getPrjImgParam; //获取工程图片参数

/*------------------------form表单数据----------------------------*/
let layerName = null;
let form = reactive({
    layer: ''
});

let rules = reactive({
    layer: [
        {
            required: true,
            message: '请选择图层',
            trigger: 'change'
        }
    ]
});

let queryType = ref([]);
const queryOptions = ['空间查询', '条件查询'];
let spatialQuery = ref(false);
let conditionalQuery = ref(false);
const queryTypeChange = (value) => {
    if (value.length === 2) {
        queryType.value.shift();
    }
    if (queryType.value.length && queryType.value[0] === '空间查询') {
        spatialQuery.value = true;
        conditionalQuery.value = false;
    } else if (queryType.value.length && queryType.value[0] === '条件查询') {
        spatialQuery.value = false;
        conditionalQuery.value = true;
    } else {
        spatialQuery.value = false;
        conditionalQuery.value = false;
    }
};

const queryText = ref(''); // 拼接的 SQL 查询语句
const selectedField = ref(null); // 当前选中的字段
const fieldValues = ref([]); // 当前字段的所有可能值
const conditions = ref(['>', '<', '=', '>=', '<=', '!=']); // 条件符号

// 添加字段到查询语句
const addFieldToQuery = (field) => {
    queryText.value = '';
    queryText.value += `${field}`;
    selectedField.value = field;
    updateFieldValues();
};

// 添加条件符号到查询语句
const addConditionToQuery = (condition) => {
    queryText.value += `${condition}`;
};
// 添加字段内容到查询语句
const addValueToQuery = (value) => {
    queryText.value += `${value}`;
};

// 根据选中的字段动态更新字段内容
const updateFieldValues = () => {
    let arr = [];
    tableData.value.forEach((item) => arr.push(item.FIELDS[selectedField.value]));
    fieldValues.value = universalSort([...new Set(arr)]);
};

//排序
function universalSort(arr, options = {}) {
    // 默认排序方式：升序
    const { ascending = true, key = null, compareFn = null } = options;

    // 如果传入了自定义比较函数，直接使用它
    if (compareFn) {
        return arr.sort(compareFn);
    }

    // 定义一个通用的比较函数
    const defaultCompareFn = (a, b) => {
        // 如果 a 和 b 是字符串形式的数字，按数字比较
        if (!isNaN(a) && !isNaN(b)) {
            return ascending ? Number(a) - Number(b) : Number(b) - Number(a);
        }

        // 如果 a 和 b 是数字，按数字比较
        if (typeof a === 'number' && typeof b === 'number') {
            return ascending ? a - b : b - a;
        }

        // 如果 a 和 b 是字符串，按字典顺序比较
        if (typeof a === 'string' && typeof b === 'string') {
            return ascending ? a.localeCompare(b) : b.localeCompare(a);
        }

        // 如果 a 和 b 是对象，根据指定的属性进行比较
        if (key !== null) {
            const valueA = a[key];
            const valueB = b[key];

            // 如果属性值是字符串形式的数字，按数字比较
            if (!isNaN(valueA) && !isNaN(valueB)) {
                return ascending ? Number(valueA) - Number(valueB) : Number(valueB) - Number(valueA);
            }

            // 如果属性值是数字，按数字比较
            if (typeof valueA === 'number' && typeof valueB === 'number') {
                return ascending ? valueA - valueB : valueB - valueA;
            }

            // 如果属性值是字符串，按字典顺序比较
            if (typeof valueA === 'string' && typeof valueB === 'string') {
                return ascending ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
            }

            // 如果属性值是其他类型，按字符串形式比较
            return ascending
                ? String(valueA).localeCompare(String(valueB))
                : String(valueB).localeCompare(String(valueA));
        }

        // 如果 a 和 b 是其他类型，按字符串形式比较
        return ascending ? String(a).localeCompare(String(b)) : String(b).localeCompare(String(a));
    };

    return arr.sort(defaultCompareFn);
}

let tableShow = ref(false); //工程表格数据
let tableData = ref([]); //工程表格数据
let pagedTableData = ref([]); //工程表格数据

let totalItems = ref(0);
let currentPage = ref(1);
let pageSize = ref(10);

const formRef = ref(); //表单ref

//每页展示的条数数量改变
const handleSizeChange = (size) => {
    pageSize.value = size;
    currentPage.value = 1;
    calculatePagedData();
};
//查询的页数改变
const handleCurrentChange = (page) => {
    currentPage.value = page;
    calculatePagedData();
};
//分页逻辑
const calculatePagedData = () => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    pagedTableData.value = tableData.value.slice(startIndex, endIndex);
    totalItems.value = tableData.value.length;
};

let sqlVal = ''; //存储sql语句
//提交表单，查询
const submitForm = (formEl, sql) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            sqlVal = sql; //sql语句保存方便修改添加后重新查询
            currentPage.value = 1; //重置页数
            query(sql);
        } else {
            ElMessage.warning('请按规则填写');
            return false;
        }
    });
};
// 重置表单
const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
    ElMessage.success('重置成功');
};

let temporaryPolygonArr = []; //用于编辑后决定进行哪种类型的查询
const query = (sql) => {
    //查询参数构建
    let getfeaturePoint = dmProjectLayer.GetFeatureMapService();

    // getfeaturePoint.type = "1"//索引
    // getfeaturePoint.strlist = "1,2,3,4"

    // getfeaturePoint.type = "2"//实体号
    // getfeaturePoint.strlist = "1,2,3,4"

    getfeaturePoint.type = '0'; //条件
    getfeaturePoint.strlayername = form.layer;
    getfeaturePoint.sql.strSql = sql && sql.length ? sql : 'dmgis_id > 0';

    // var rect = new dmgis.object.Envelope();
    // rect.minx
    // getfeaturePoint.sql.env  = rect;//矩形
    // getfeaturePoint.sql.strPos = "";//多边形

    dmProjectLayer.SendFeatureMapService(getfeaturePoint).then((res) => {
        if (res) {
            ElMessage.success('查询成功');

            layerName = form.layer; //存放当前表格的图层名
            //请求与表格结果对应的工程图片
            getPrjImgParam = {
                name: 'QUERY',
                singleLabel: true,
                attributes: {
                    where: sql && sql.length ? sql : 'dmgis_id > 0'
                }
            };
            addDmProject();

            temporaryPolygonArr = []; //重置为条件查询
            //两种情况，返回结果为对象则转为数组用来渲染表格
            if (!Object.hasOwn(res.RESPONSE.FEATURES, 'FEATURE') && res.RESPONSE.FEATURES) {
                tableData.value = [];
            } else if (res.RESPONSE.FEATURES.FEATURE.length) {
                tableData.value = res.RESPONSE.FEATURES.FEATURE;
            } else {
                tableData.value = [res.RESPONSE.FEATURES.FEATURE];
            }
            calculatePagedData(); //分页计算
            tableShow.value = true;
            // console.log(tableData.value);
        } else {
            ElMessage.error('查询失败');
        }
    });
};

const fieldsKeys = computed(() => {
    if (tableData.value.length > 0) {
        //获取表头
        // console.log('fieldsKeys', tableData.value[0]);
        return Object.keys(tableData.value[0].FIELDS);
    } else {
        return [];
    }
});

/*------------------------------------------------------条件查询--------------------------------------------------------- */

/*------------------------------------------------------空间查询--------------------------------------------------------- */
let dialogFormVisible1 = ref(false); //显示半径输入弹窗
let formData1 = reactive({ radius: '' }); //存放半径
const bufferFormRef = ref(); //buffer表单ref
let rules1 = reactive({
    radius: [
        {
            required: true,
            message: '请输入半径',
            trigger: 'change'
        },
        {
            validator: (rule, value, callback) => {
                if (!/^\d+(\.\d+)?$/.test(value)) {
                    callback(new Error('请输入有效的数字'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ]
});
let temporaryCoordinates; //创建缓冲区的原始矢量坐标
let temporaryType; //临时缓冲区类型

//绘制后空间查询
const queryDraw = (type) => {
    olMap.value.draw.startDrawing(type, false, (coordinates) => {
        // console.log('绘制的坐标：', formatCoordinates(coordinates));
        if (type === 'LineString' || type === 'Point') {
            if (type === 'LineString') {
                temporaryType = 'line';
                temporaryCoordinates = coordinates[0];
            } else if (type === 'Point') {
                temporaryType = 'point';
                temporaryCoordinates = coordinates[0][0];
            }
            formData1 = reactive({}); //重置表格
            dialogFormVisible1.value = true;
        } else {
            pointArr.value = coordinates;
            bufferQuery(formatCoordinates(pointArr.value));
        }
    });
};

//创建缓冲区
const createBuffer = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            bufferQuery(
                formatCoordinates(
                    olMap.value.draw.createBuffer(temporaryCoordinates, Number(formData1.radius) * 1000, temporaryType)
                )
            );
            dialogFormVisible1.value = false;
        } else {
            ElMessage.warning('请按规则填写');
            return false;
        }
    });
};
const bufferQuery = (coordinates) => {
    if (!form.layer) {
        ElMessage.warning('请选择图层');
        return false;
    }
    temporaryPolygonArr = coordinates;
    //查询参数构建
    let getfeaturePoint = dmProjectLayer.GetFeatureMapService();

    getfeaturePoint.type = '0'; //条件
    getfeaturePoint.strlayername = form.layer;
    getfeaturePoint.sql.strPos = coordinates; //多边形

    dmProjectLayer.SendFeatureMapService(getfeaturePoint).then((res) => {
        if (res) {
            ElMessage.success('查询成功');

            layerName = form.layer; //存放当前表格的图层名
            //请求与表格结果对应的工程图片
            getPrjImgParam = {
                name: 'POLYGON',
                singleLabel: true,
                attributes: {
                    coords: coordinates
                }
            };
            addDmProject();

            //两种情况，返回结果为对象则转为数组用来渲染表格
            if (!Object.hasOwn(res.RESPONSE.FEATURES, 'FEATURE') && res.RESPONSE.FEATURES) {
                tableData.value = [];
            } else if (res.RESPONSE.FEATURES.FEATURE.length) {
                tableData.value = res.RESPONSE.FEATURES.FEATURE;
            } else {
                tableData.value = [res.RESPONSE.FEATURES.FEATURE];
            }
            calculatePagedData(); //分页计算
            tableShow.value = true;
            // console.log(tableData.value);
        } else {
            ElMessage.error('查询失败');
        }
    });
};

function formatCoordinates(coords) {
    // 使用 map 遍历二维数组，将每组坐标转换为字符串
    const formatted = coords[0].map((pair) => pair.join(' '));
    // 使用 join 方法将所有字符串用分号分隔
    return formatted.join(';');
}
/*------------------------------------------------------空间查询--------------------------------------------------------- */

/*------------------------------------------------------工程图片加载--------------------------------------------------------- */
let moveEndListener = null; // 用于保存事件监听器的引用
let serviceLayer = null; //工程图层
let isMoveEndBound = false; // 标记是否已绑定
//加载工程图片
const addDmProject = () => {
    if (olMap.value.layer.getLayerByName('工程图片图层')) {
        olMap.value.map.removeLayer(olMap.value.layer.getLayerByName('工程图片图层'));
    }

    dmProjectLayer.serviceLayer = new ImageLayer();
    dmProjectLayer.serviceLayer.setZIndex(2);

    serviceLayer = dmProjectLayer.serviceLayer;
    serviceLayer.set('layerName', '工程图片图层');

    let imgSvrParam = dmProjectLayer.ImgMapService;

    let extent = olMap.value.map.getView().calculateExtent(olMap.value.map.getSize());
    let size = olMap.value.map.getSize();
    //填参
    imgSvrParam.DispRect.minx = extent[0];
    imgSvrParam.DispRect.miny = extent[1];
    imgSvrParam.DispRect.maxx = extent[2];
    imgSvrParam.DispRect.maxy = extent[3];
    imgSvrParam.imgWid = size[0];
    imgSvrParam.imgHig = size[1];

    let param = {
        name: 'DMGISXML',
        version: '1.1',
        children: {
            name: 'REQUEST',
            children: {
                name: 'GET_IMAGE',
                attributes: {
                    minx: extent[0],
                    miny: extent[1],
                    maxx: extent[2],
                    maxy: extent[3],
                    width: size[0],
                    height: size[1],
                    bclr: '255,255,255',
                    disp: '0'
                },
                children: {
                    name: 'LAYERLIST',
                    children: {
                        name: 'LAYERDEF',
                        attributes: {
                            name: layerName,
                            visible: 1
                        },
                        // children: {
                        //     name: 'DISPHIGH',
                        //     attributes: {
                        //         type: 0,
                        //         objtype: 0
                        //     },
                        children: getPrjImgParam
                        // }
                    }
                }
            }
        }
    };

    //通过RefreshMap动态获取工程图片，实现地图的刷新
    dmProjectLayer.RefreshMap(serviceLayer, dmProjectLayer.ImgMapService, param, olMap.value.map.getView().getZoom());
    olMap.value.map.addLayer(serviceLayer);

    // 保存事件监听器的引用
    moveEndListener = function (evt) {
        let frameState = evt.frameState;
        // 填参
        imgSvrParam.DispRect.minx = frameState.extent[0];
        imgSvrParam.DispRect.miny = frameState.extent[1];
        imgSvrParam.DispRect.maxx = frameState.extent[2];
        imgSvrParam.DispRect.maxy = frameState.extent[3];
        imgSvrParam.imgWid = frameState.size[0];
        imgSvrParam.imgHig = frameState.size[1];

        let param = {
            name: 'DMGISXML',
            version: '1.1',
            children: {
                name: 'REQUEST',
                children: {
                    name: 'GET_IMAGE',
                    attributes: {
                        minx: frameState.extent[0],
                        miny: frameState.extent[1],
                        maxx: frameState.extent[2],
                        maxy: frameState.extent[3],
                        width: frameState.size[0],
                        height: frameState.size[1],
                        bclr: '255,255,255',
                        disp: '0'
                    },
                    children: {
                        name: 'LAYERLIST',
                        children: {
                            name: 'LAYERDEF',
                            attributes: {
                                name: layerName,
                                visible: 1
                            },
                            // children: {
                            //     name: 'DISPHIGH',
                            //     attributes: {
                            //         type: 0,
                            //         objtype: 0
                            //     },
                            children: getPrjImgParam
                            // }
                        }
                    }
                }
            }
        };
        dmProjectLayer.RefreshMap(serviceLayer, imgSvrParam, param, frameState.viewState.zoom);
    };

    //第一次添加moveend事件
    if (!isMoveEndBound) {
        olMap.value.map.on('moveend', moveEndListener);
        isMoveEndBound = true;
    }
};

//移除工程图片图层
const removeDmProject = () => {
    // 移除事件监听器
    if (moveEndListener) {
        olMap.value.map.un('moveend', moveEndListener);
        moveEndListener = null;
        isMoveEndBound = false;
    }
    if (dmProjectLayer.serviceLayer) {
        olMap.value.map.removeLayer(olMap.value.layer.getLayerByName('工程图片图层'));
        dmProjectLayer.serviceLayer = null;
        serviceLayer = null;
    }
};
/*------------------------------------------------------工程图片加载--------------------------------------------------------- */

/*------------------------------------------------------矢量属性修改--------------------------------------------------------- */
const isEditing = ref(false); //input框是否显示
const editingCell = ref(null); //当前正在编辑的单元格
const editData = ref(''); //input框的值
const lastEditData = ref(''); //input框的值

// 双击单元格时，显示input框
const editCell = (rowIndex, cellIndex, value, row) => {
    if (!editModel) {
        return;
    }
    isEditing.value = true;
    editingCell.value = `${rowIndex}-${cellIndex}`;
    editData.value = value;
    lastEditData.value = value;

    //使input框的宽度和单元格相同
    const target = document.getElementById('edit-target' + rowIndex + '-' + cellIndex);
    const currentWidth = target.offsetWidth;
    const currentHeight = target.offsetHeight;
    nextTick(() => {
        const input = document.getElementById('edit-input');
        if (input) {
            // 聚焦并设置宽度
            document.getElementById('edit-input').focus();
            input.style.width = `${currentWidth}px`;
            input.style.height = `${currentHeight - 1}px`;
        }
    });
};

// 保存修改
const saveEdit = (row, info, rowIndex, cellIndex) => {
    isEditing.value = false;
    editingCell.value = null;

    // 如果输入框的值没有变化，则不执行后续操作
    if (lastEditData.value === editData.value) {
        return;
    }

    if (!editData.value.length) {
        ElMessage.warning('值不能为空！');
        return;
    }

    let getbuildPoint = dmProjectLayer.GetBuildMapService(layerName);

    //如果属性修改了
    getbuildPoint.type = '3';
    getbuildPoint.index = row.index;

    getbuildPoint.rco = [info];
    dmProjectLayer.SendBuildMapService(getbuildPoint).then((res) => {
        if (res.RESPONSE.OBJ.SC === '1') {
            ElMessage.success('修改成功');

            dmProjectLayer.savePrj(getbuildPoint, layerName); //保存工程

            //编辑后进行上次相同条件或空间查询
            if (temporaryPolygonArr.length) {
                bufferQuery(temporaryPolygonArr);
            } else {
                query(sqlVal); //查询表格
            }

            // tableData.value[rowIndex].FIELDS[fieldsKeys.value[cellIndex]] = info.fldval;//前端静态修改
        } else if (res.RESPONSE.OBJ.SC === '0') {
            ElMessage.error('修改失败');
        }
    });

    //坐标修改
    // if (row.POS.type === '0') {
    //     getbuildPoint.strPos = row.POS.pnt;
    // } else if (row.POS.type === '1') {
    //     getbuildPoint.strPos = row.POS.cod;
    // }
};
/*------------------------------------------------------矢量属性修改--------------------------------------------------------- */

/*------------------------------------------------------矢量添加--------------------------------------------------------- */

let dialogFormVisible = ref(false); //显示新建矢量弹窗
let formData = reactive({}); //存放新建矢量的表单数据

let pointArr = ref([]); //存放点坐标
const draw = (type) => {
    if (!tableShow.value) {
        return ElMessage.warning('请先进行图层信息查询');
    }

    olMap.value.draw.startDrawing(type, false, (coordinates) => {
        // console.log('绘制的坐标：', coordinates, formatCoordinates(coordinates));
        dialogFormVisible.value = true;
        pointArr.value = coordinates;
    });
};

const addVector = () => {
    console.log(formData, 'addVector');

    let getbuildPoint = dmProjectLayer.GetBuildMapService(layerName);

    //添加实体
    getbuildPoint.type = '0';
    getbuildPoint.rco = Object.entries(formData).map(([key, value]) => ({
        fldname: key,
        fldval: value
    }));

    getbuildPoint.strPos = formatCoordinates(pointArr.value); //坐标

    dmProjectLayer.SendBuildMapService(getbuildPoint).then((res) => {
        if (res.RESPONSE.OBJ.SC === '1') {
            ElMessage.success('添加成功');
            dialogFormVisible.value = false; //关闭弹窗
            formData = reactive({}); //重置表格

            dmProjectLayer.savePrj(getbuildPoint, layerName); //保存工程

            query(sqlVal); //查询表格
        } else if (res.RESPONSE.OBJ.SC === '0') {
            dialogFormVisible.value = false; //关闭弹窗
            formData = reactive({}); //重置表格
            ElMessage.error('添加失败');
        }
    });
};
/*------------------------------------------------------矢量添加--------------------------------------------------------- */
</script>
<style lang="less" scoped>
.fade-enter-active,
.fade-leave-active {
    transition: all 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
    transform: scale(0.5);
}

.data-table {
    background: var(--theme-item-bg);
    padding-top: var(--system-map-item-padding);
    border-radius: var(--system-map-item-radius);

    display: flex;
    flex-direction: column; /*设置为垂直方向*/
    align-items: center;
    gap: 1vh;

    table {
        width: 100%;
        border-collapse: collapse;
    }
    th,
    td {
        font-size: 0.75vw;
        color: var(--theme-text1);
        padding: 0.5vw;
        text-align: left;
        border-bottom: 1px solid #ddd;
        cursor: pointer;

        // max-width: 6vw;
    }
}

.query-builder {
    display: flex;
    flex-direction: column; /*设置为垂直方向*/
    align-items: center; /*左右居中*/
    justify-content: center;
    width: 100%;
    gap: 0.5vh;
    margin-bottom: 1vh;
    .input-box {
        width: 80%;
        margin-bottom: 0.5vh;
    }

    .input-box input {
        width: 100%;
        padding: 8px;
        font-size: 14px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
    }
    .select-body {
        min-width: 80%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 0.5vh;
        .field-values,
        .conditions {
            display: flex;
            flex-direction: column;
            height: 12vh;
            overflow-y: auto;
            gap: 5px;
            padding: 5px 10px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;

            .field-label,
            .condition-label {
                color: var(--theme-text);
                font-size: 0.75vw;
                font-weight: bold;
                margin-right: 10px;
            }

            .field-value,
            .condition {
                color: var(--theme-text);
                font-size: 0.7vw;
                cursor: pointer;
            }
        }
    }
}

.slide-enter-active,
.slide-leave-active {
    transition: transform 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
    transform: translateX(100%);
}

.slide-enter-to,
.slide-leave-from {
    transform: translateX(0);
}
</style>
